//
//  WDWorkOrderViewController.m
//  wd-serviceapp
//
//  Created by Bin Tang on 2024/8/2.
//

#import "WDWorkOrderViewController.h"
#import "WDWorkOrderViewModel.h"
#import "TYZBaseTableViewController.h"
#import "TYZBaseCollectionViewController.h"
#import "WDWorkOrderTopView.h"
#import "WDWorkOrderCurrentCondView.h" // 当前筛选视图
#import "WDWorkOrderHistoryCondView.h" // 历史筛选视图

@interface WDWorkOrderViewController () <TYZPageViewControllerDelegate, TYZPageViewControllerDataSource>
@property (nonatomic, strong) WDWorkOrderViewModel *viewModel;

@property (nonatomic, strong) WDWorkOrderTopView *topView;

/// 当前筛选视图
@property (nonatomic, strong) WDWorkOrderCurrentCondView *currCondView;

/// 历史筛选视图
@property (nonatomic, strong) WDWorkOrderHistoryCondView *historyCondView;

@end

@implementation WDWorkOrderViewController

- (void)dealloc
{
    debugMethod();
}

- (void)initWithVar
{
    [super initWithVar];
    
}

- (void)initWithViewModel
{
    _viewModel = [WDWorkOrderViewModel new];
    
}

- (void)initWithNavBar
{
    [super initWithNavBar];
    
    self.navigationItem.title = self.viewModel.title;
    
//    [self initWithNavRight];
}

- (void)initWithSubView
{
    [self initWithServiceTopView];
    self.dataSource = self;
    self.delegate = self;
    
    [super initWithSubView];
    
    [self initWithCurrCondView];
    
    [self initWithHistoryCondView];
    
}

/// 初始化右上角的按钮
- (void)initWithNavRight
{
    UIImage *image = [UIImage imageNamed:@"ic_nav_scan_code"];
    CGRect frame = CGRectMake(0, 0, 30, 30);
    UIButton *btnRight = [UIButton createWithButton:nil frame:frame font:FONTSIZE(16) target:self action:@selector(actionWithNavRight:) propertiesBlock:^(UIButton * _Nonnull button) {
        [button setImage:image forState:UIControlStateNormal];
    }];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:btnRight];
    self.navigationItem.rightBarButtonItem = rightItem;
}

/// 当前筛选视图
- (void)initWithCurrCondView {
    if (!_currCondView) {
        CGRect frame = CGRectMake(0, kWDWorkOrderTopViewHeight + NAVBAR_HEIGHT_STATUS, kScreenW, self.viewModel.currentViewHeight);
        _currCondView = [[WDWorkOrderCurrentCondView alloc] initWithFrame:frame];
    }
}

/// 历史筛选视图
- (void)initWithHistoryCondView {
    if (!_historyCondView) {
        CGRect frame = CGRectMake(0, kWDWorkOrderTopViewHeight + NAVBAR_HEIGHT_STATUS, kScreenW, self.viewModel.historyViewHeight);
        _historyCondView = [[WDWorkOrderHistoryCondView alloc] initWithFrame:frame];
    }
}

/// 点击右上角按钮事件
/// - Parameter sender: sender description
- (void)actionWithNavRight:(id)sender
{
//    [SVProgressHUD showInfoWithStatus:@"扫码"];
}

- (void)initWithServiceTopView
{
    if (!_topView) {
        CGRect frame = CGRectMake(0, 0, kScreenW, kWDWorkOrderTopViewHeight);
        _topView = [[WDWorkOrderTopView alloc] initWithFrame:frame];
        self.headerView = _topView;
        @weakify(self);
        // 点击搜索框 - 进入搜索页面
        _topView.touchSearchBlock = ^(NSString * _Nonnull searchMsg) {
            @strongify(self);
            [self actionWithSearchMsg: searchMsg];
        };
        // 筛选 -- 点击筛选按钮
        _topView.touchFiltrateBlock = ^{
            @strongify(self);
            [self actionWithFiltrate];
        };
    }
}

/// 筛选 -- 点击筛选按钮
- (void)actionWithFiltrate {
    @weakify(self);
    if (self.pageIndex == 0) { // 当前工单
        [self.currCondView showWithTitle:@"" data:self.viewModel completion:^{
            @strongify(self);
            [self.currCondView hide];
            [self sendFiltrateNoti:0]; // 当前工单
        } failed:^{
            @strongify(self);
            [self.currCondView hide];
        }];
    } else if (self.pageIndex == 1) { // 历史工单
        [self.historyCondView showWithTitle:@"" data:self.viewModel completion:^{
            @strongify(self);
            [self.historyCondView hide];
            [self sendFiltrateNoti:1]; // 历史工单
        } failed:^{
            @strongify(self);
            [self.historyCondView hide];
        }];
    }
}

/// 发送筛选通知
/// - Parameter type: 0当前工单 1历史工单
- (void)sendFiltrateNoti:(NSInteger)type {
    self.viewModel.reqModel.searchType = @(type);
    self.viewModel.reqModel.startTime = nil;
    self.viewModel.reqModel.endTime = nil;
    self.viewModel.reqModel.engineerId = nil;
    self.viewModel.reqModel.servFlow = nil;
    
    TYZCommonCellModel *model = nil;
    if (type == 0) { // 当前工单
        for (TYZCommonCellModel *ent in self.viewModel.currentDates) {
            if (ent.isCheck) {
                model = ent;
                break;
            }
        }
        [self parseWithDate:model];
        model = nil;
        
        for (TYZCommonCellModel *ent in self.viewModel.currentOrderStatus) {
            if (ent.isCheck) {
                model = ent;
                self.viewModel.reqModel.servFlow = [NSString stringWithFormat:@"%zd", model.index];
                break;
            }
        }
        model = nil;
        
        for (TYZCommonCellModel *ent in self.viewModel.currentOperators) {
            if (ent.isCheck) {
                model = ent;
                if ([ent.title isEqualToString:@"我经手的"]) {
                    self.viewModel.reqModel.engineerId = @([EDSAppDelegateTool sharedInstance].userInfoModel.id);
                } else {
                    self.viewModel.reqModel.engineerId = nil;
                }
                break;
            }
        }
    } else { // 历史工单
        for (TYZCommonCellModel *ent in self.viewModel.historyDates) {
            if (ent.isCheck) {
                model = ent;
                break;
            }
        }
        [self parseWithDate:model];
        model = nil;
        
        for (TYZCommonCellModel *ent in self.viewModel.historyOrderStatus) {
            if (ent.isCheck) {
                model = ent;
                self.viewModel.reqModel.servFlow = [NSString stringWithFormat:@"%zd", model.index];
                break;
            }
        }
        model = nil;
        
        for (TYZCommonCellModel *ent in self.viewModel.historyOperators) {
            if (ent.isCheck) {
                model = ent;
                if ([ent.title isEqualToString:@"我经手的"]) {
                    self.viewModel.reqModel.engineerId = @([EDSAppDelegateTool sharedInstance].userInfoModel.id);
                } else {
                    self.viewModel.reqModel.engineerId = nil;
                }
                break;
            }
        }
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kWORK_ORDER_FILTRATE_NOTI object:self.viewModel.reqModel];
    
}

/// 解析时间
/// - Parameter model: model description
- (void)parseWithDate:(TYZCommonCellModel *)model {
    if (model == nil) {
        return;
    }
    
    NSDate *now = [NSDate date];
    if ([model.title isEqualToString:@"最近七天"]) {
        NSDate *startDate = [now getPreviousDate:1 andNum:7];
        self.viewModel.reqModel.startTime = [NSString stringWithFormat:@"%@ 00:00:00", [startDate stringWithFormat:@"yyyy-MM-dd"]];
        self.viewModel.reqModel.endTime = [NSString stringWithFormat:@"%@ 23:59:59", [now stringWithFormat:@"yyyy-MM-dd"]];
    } else if ([model.title isEqualToString:@"当月"]) {
        NSString *startDateStr = [NSDate getMonthFirstDay:[now stringWithFormat:@"yyyy-MM-dd"] format:@"yyyy-MM-dd"];
        self.viewModel.reqModel.startTime = [NSString stringWithFormat:@"%@ 00:00:00", startDateStr];
        self.viewModel.reqModel.endTime = [NSString stringWithFormat:@"%@ 23:59:59", [now stringWithFormat:@"yyyy-MM-dd"]];
    } else if ([model.title isEqualToString:@"三个月内"]) {
        NSDate *startDate = [now getPreviousDate:2 andNum:3];
        self.viewModel.reqModel.startTime = [NSString stringWithFormat:@"%@ 00:00:00", [startDate stringWithFormat:@"yyyy-MM-dd"]];
        self.viewModel.reqModel.endTime = [NSString stringWithFormat:@"%@ 23:59:59", [now stringWithFormat:@"yyyy-MM-dd"]];
    } else if ([model.title isEqualToString:@"半年内"]) {
        NSDate *startDate = [now getPreviousDate:2 andNum:6];
        self.viewModel.reqModel.startTime = [NSString stringWithFormat:@"%@ 00:00:00", [startDate stringWithFormat:@"yyyy-MM-dd"]];
        self.viewModel.reqModel.endTime = [NSString stringWithFormat:@"%@ 23:59:59", [now stringWithFormat:@"yyyy-MM-dd"]];
    } else if ([model.title isEqualToString:@"今年"]) {
        self.viewModel.reqModel.startTime = [NSString stringWithFormat:@"%zd-01-01 00:00:00", now.year];
        self.viewModel.reqModel.endTime = [now stringWithFormat:@"yyyy-MM-dd HH:mm:ss"];
    } else if ([model.title isEqualToString:@"全部"]) {
        self.viewModel.reqModel.startTime = nil;
        self.viewModel.reqModel.endTime = nil;
    }
//    debugLog(@"start=%@; end=%@", self.viewModel.reqModel.startTime, self.viewModel.reqModel.endTime);
//    debugLog(@"dd");
}

/// 点击搜索
/// - Parameter msg: msg description
- (void)actionWithSearchMsg:(NSString *)msg {
    
//    self.pageIndex
    
    
    NSDictionary *params = @{
        @"searchMsg": objectNull(msg),
        @"searchType": @(self.pageIndex), // 工单类型
    };
    UIViewController *vc = [[TYZRouter sharedInstance] getWorkOrderSearchVC:params];
    [TYZJumpVCManager pushBaseVC:self pushVC:vc];
}

+ (TYZPageConfigration *)setupConfig
{
    TYZPageConfigration *config = [TYZPageConfigration defaultConfigration];
    config.pageStyle = TYZPageStyleSuspensionCenter; //TYZPageStyleSuspensionTop;
    config.headerViewCouldScale = YES;
    config.headerViewScaleMode = TYZPageHeaderViewScaleModeTop;
//    config.headerViewCouldScrollPage = NO;
    config.showTabbar = YES;
    config.showNavigation = YES;
    config.aligmentModeCenter = NO;
    config.lineWidthEqualFontWidth = YES; // 变为平分时 是否需要线条宽度等于字体宽度 默认 NO
    config.showBottomLine = NO;
    config.scrollMenu = NO;
    config.itemMargin = 20;
    
    config.aligmentModeCenter = NO;
    config.lineHeight = 2;
//    config.lineWidth = 30;
    config.lineColor = kThemeColor;
    
//    config.cutOutHeight = kWDWorkOrderTopViewHeight;
    config.suspenOffsetY = kWDWorkOrderTopViewHeight;//NAVBAR_HEIGHT_STATUS; // 设置悬浮停顿偏移量
    
    config.itemFont = [UIFont systemFontOfSize:14 weight:UIFontWeightRegular];
    config.selectedItemFont = [UIFont systemFontOfSize:14 weight:UIFontWeightRegular];
    config.normalItemColor = [UIColor colorWithHexString:@"#6C7482"];
    config.selectedItemColor = [UIColor colorWithHexString:@"#000000"];;
    config.scrollViewBackgroundColor = kWhiteColor;
    
    return config;
}

+ (NSArray *)setupMenuTitles {
    return @[@"当前工单", @"历史工单"];
}

+ (NSArray *)setupViewControllers:(NSDictionary *)param {
    NSArray *titles = [self setupMenuTitles];
    NSMutableArray *vcs = @[].mutableCopy;
    for (int i=0; i<titles.count; i++) {
        NSString *title = titles[i];
        NSMutableDictionary *mutDict = [NSMutableDictionary dictionaryWithDictionary:param];
        mutDict[@"servType"] = @(i);
        UIViewController *vc = [[TYZRouter sharedInstance] getWorkOrderItemVC:mutDict];
        [vcs addObject:vc];
    }
    return vcs;
}


#pragma mark - TYZPageViewControllerDelegate, TYZPageViewControllerDataSource
- (UIScrollView *)pageViewController:(TYZPageViewController *)pageViewController pageForIndex:(NSInteger)index
{
    UIViewController *vc = pageViewController.controllerList[index];
    
    if ([vc isKindOfClass:[TYZBaseTableViewController class]])
    {
        return ((TYZBaseTableViewController *)vc).baseTableView;
    }
    else if ([vc isKindOfClass:[TYZBaseCollectionViewController class]]) {
        return ((TYZBaseCollectionViewController *)vc).baseCollectionView;;
    }
    return nil;
}

- (void)pageViewController:(TYZPageViewController *)pageViewController contentOffsetY:(CGFloat)contentOffsetY progress:(CGFloat)progress
{
    
}

- (void)pageViewController:(TYZPageViewController *)pageViewController didScrollMenuItem:(UIButton *)itemButton index:(NSInteger)index
{
    
}

@end
